﻿using System;
using System.Collections.Generic;

using System.Reflection;
using System.Text;

namespace QQZiFramework
{
    /// <summary>
    /// 属性信息（包括自定义属性）
    /// </summary>
    public class CustomerProperty
    {
        public PropertyInfo Info { get; set; }
        public DBFieldAttribute Attr { get; set; }

        public string GetDBFieldName(object instance)
        {
            if (Attr == null || string.IsNullOrEmpty(Attr.FieldName))
            {
                if(instance == null) return Info.Name;
                //没有自定义属性的，判断有没有重写字段
                EntityLoaderInfo loaderInfo = EntityLoaderInfo.GetEntityLoaderInfo(instance.GetType());               
                if (loaderInfo.OverrideFieldInfo == null) return Info.Name;//直接返回PropertyInfo名字
                else
                {
                    //有重载的，获取重载的名字
                    IDictionary<string, string> overriteDic = loaderInfo.OverrideFieldInfo.GetValue(instance) as IDictionary<string, string>;
                    if (overriteDic == null) return Info.Name;
                    else
                    {
                        string overrideName;
                        if (overriteDic.TryGetValue(Info.Name, out overrideName)) return overrideName;
                        else return Info.Name;
                    }
                }
            }
            else
            {
                return Attr.FieldName;
            }
        }

        public bool IsPrimaryKey()
        {
            return Attr != null && Attr.Usage == DBFieldUsage.PrimaryKey;
        }
    }
}
